package com.vf.s.mvc.scene.controller;

import java.util.List;

import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.vf.core.controller.BaseController;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.cache.style.MapLayerCache;
import com.vf.s.common.cache.style.MapStyleCache;
import com.vf.s.common.model.biz.BizMap;
import com.vf.s.common.model.biz.BizModel;
import com.vf.s.common.model.scene.*;
import com.vf.s.mvc.sys.service.DicService;
public class BizSceneContoller  extends BaseController{

	@Inject
	private DicService dicSrv;
	
	public void editor() {
		this.setAttr("scene",BizScene.dao.findById(this.getPara("sceneId")));
		this.setAttr("types",dicSrv.findItemList("sceneMenuType"));
		render("editor.html");
	}

	public void setting() {
		this.setAttr("scene", BizScene.dao.findById(this.getPara("sceneId")));
		render("setting.html");
	}
	
	public void save() {
		BizScene model = getModel(BizScene.class);
		if (StrKit.notBlank(model.getId())) {
			if (model.update()) {
				renderSuccess("更新成功！", BizScene.dao.findById(model.getId()));
			} else {
				renderError("更新失败！");
			}
		} else {
			model.setId(UuidUtil.getUUID());
			if (model.save()) {
				renderSuccess("保存成功！",BizScene.dao.findById(model.getId()));
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	/**
	 * 获取场景
	 */
	public void getById() {
		String sceneId = getPara("sceneId");
		BizScene scene = BizScene.dao.findById(sceneId);
		if(scene==null) {
			renderError("场景不存在!");
			return;
		}
		if(StrKit.equals(this.getPara("hasMap"),"1")) {
			String whereForMap="SELECT A.* FROM "+BizMap.TABLE_NAME+" A , "+BizSceneMap.TABLE_NAME+" B WHERE A.ID=B.MAPID AND B.SCENEID=? ";
			if(!StrKit.isBlank(sceneId)) {
				whereForMap+=" AND B.SCENEID='"+sceneId+"' ";
			}
			whereForMap+=" ORDER BY B.SORT ASC ";
			List<BizMap> maps=BizMap.dao.find(whereForMap,sceneId);
			scene.setMaps(maps);
		}
		
		
		if(StrKit.equals(this.getPara("hasModel"),"1")) {
			String whereForBizModelParam="FROM "+BizSceneModel.TABLE_NAME+" A, "+BizModel.TABLE_NAME+" B WHERE A.MODELID=B.ID and A.SCENEID=?  ";
			if(!StrKit.isBlank(sceneId)) {
				whereForBizModelParam+=" and  A.SCENEID='"+sceneId+"' ";
			}
			whereForBizModelParam+=" ORDER BY A.SORT ASC ";
			List<BizSceneModel> models=BizSceneModel.dao.find("SELECT A.*,B.URL AS uri  "+whereForBizModelParam,sceneId);
			scene.setModels(models);
		}
		scene.setMapStyle(MapStyleCache.gets());
		scene.setMapLayer(MapLayerCache.gets());
		renderSuccess("成功！",scene);
	}
	
}
